package com.yuanxiao.controller;

import com.yuanxiao.pojo.Article;
import com.yuanxiao.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    private ArticleService service;

    @RequestMapping("/toLoginPage")
    public String tologinPage(Model model){
        model.addAttribute("currentYear", Calendar.getInstance().get(Calendar.YEAR));
        return "login";
    }

    @RequestMapping("/toindex")
    public String toindex(Model model, HttpServletRequest request){
        //没有传分页参数,则给定默认的参数
        Integer page =request.getParameter("page")==null?0: Integer.valueOf(request.getParameter("page"));
        Integer size =request.getParameter("size")==null?3: Integer.valueOf( request.getParameter("size"));
        //当时首页时.点击上一页,判定查首页
        if(page<=0){
            page=0;
        }

        Page<Article> all = service.getAll(page, size);
        int totalPages = all.getTotalPages();
        //没有数据则是在最后一页点了下一页. 则查询最后一页数据返回
        if(all.getContent().size()<=0){
            page=page-1;
            all = service.getAll(page, size);
        }
        model.addAttribute("list",all.getContent());//数据
        model.addAttribute("totalPages",totalPages);//总页数
        model.addAttribute("size",all.getTotalElements());//总条数
        model.addAttribute("cupage",page);//当前页 0开始

        return "client/index";
    }
}
